<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Files</title>
<link rel="stylesheet" href="/cfg/format.css" type="text/css">
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="keywords" content="Python, files, tutorial, programming language, learn Python">
<meta name="description" content="In this chapter of the Python tutorial,
we will cover files.">
<meta name="language" content="en">
<meta name="author" content="Jan Bodnar">
<meta name="distribution" content="global">

<script type="text/javascript" src="/lib/jquery.js"></script>
<script type="text/javascript" src="/lib/common.js"></script>

</head>

<body>

<div class="container">

<div id="wide_ad" class="ltow">
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* 160x600, August 2011 */
google_ad_slot = "2484182563";
google_ad_width = 160;
google_ad_height = 600;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>

<div class="content">

<a href="/" title="Home">Home</a>&nbsp;
<a href="..">Contents</a>


<h1>Files</h1>

<p>
In this part of the Python programming tutorial, we will talk about files. 
</p>

<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* NewSquare */
google_ad_slot = "0364418177";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script> 
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> 
</script>  

<p>
Everything in Python is an object. Everything in UNIX is a file. 
</p>

<h2>Standard I/O</h2>

<p>
There are three basic I/O connections. <b>Standard input</b>, 
<b>standard output</b> and <b>standard error</b>. Standard input is 
the data that goes to the program. The standard input comes from a keyboard.
Standard output is where we print our data with the print keyword. 
Unless redirected, it is the terminal console. 
The standard error is a stream where programs write their error messages.
It is usually the text terminal. 
</p>

<p>
Conforming to the UNIX philosophy, the standard I/O streams are file objects. 
</p>

<h2>Standard input</h2>

<p>
Standard input is the data that goes to the program.
</p>

<pre class="code">
#!/usr/bin/python

# name.py

import sys


print 'Enter your name: ',

name = ''

while True:
   c = sys.stdin.read(1)
   if c == '\n':
      break
   name = name + c

print 'Your name is:', name
</pre>

<p>
In order to work with standard I/O streams, we must import the <code>sys</code> module. 
The <code>read()</code> method reads one character from the standard 
input. In our example we get a promt saying "Enter your name". We enter our name 
and press enter. The enter key generates the <b>new line</b> character: <b>\n</b>. 
</p>

<pre>
$ ./name.py 
Enter your name: Jan
 Your name is: Jan
</pre>

<p>
For getting input we can use higher level functions: <code>input()</code> 
and <code>raw_input()</code> .
</p>

<p>
The <code>input()</code> function prints a prompt if it is given, 
reads input and evaluates it. 
</p>

<pre class="code">
#!/usr/bin/python

# input.py


data = input('Enter expression: ')

print 'You have entered:', data
</pre>

<pre>
$ ./input.py 
Enter expression: 3*3
You have entered: 9
</pre>


<p>
The <code>raw_input()</code> prints a  prompt if it is present. 
The function then reads a line from input, converts it to a string (stripping 
a trailing newline), and returns that. 
</p>

<pre class="code">
#!/usr/bin/python

# rawinput.py


name = raw_input('Enter your name: ')

print 'You have entered:', name
</pre>


<h2>Standard output</h2>

<p>
The standard output is where we print our data. 
</p>

<pre class="code">
#!/usr/bin/python

# stdout.py

import sys

sys.stdout.write('Honore de Balzac, Father Goriot\n')
sys.stdout.write('Honore de Balzac, Lost Illusions\n')
</pre>

<p>
In the example, we write some text to the standard output. This is in our 
case the terminal console. We use the
<code>write()</code> method. 
</p>

<pre class="code">
$ ./stdout.py 
Honore de Balzac, Father Goriot
Honore de Balzac, Lost Illusions
</pre>

<p>
The <code>print</code> keyword puts some text into the 
<code>sys.stdout</code> by default. 
</p>

<pre class="code">
#!/usr/bin/python

# printkeyw.py

print 'Honore de Balzac, The Splendors and Miseries of Courtesans'
print 'Honore de Balzac, Gobseck'
</pre>

<p>
We do not provide the sys.stdout explicitly. It is done behind the scenes. 
There is another form of the print keyword. If we want, we can use it to 
write some data into a regular file. 
</p>


<pre class="code">
#!/usr/bin/python

# works.py

f = open('works', 'w')

print >> f, 'Beatrix'
print >> f, 'Honorine'
print >> f, 'The firm of Nucingen'

f.close()
</pre>

<p>
We open a file and write three titles of Balzac books into it. This form is 
also called <b>print chevron</b>.
</p>

<pre>
$ cat works
Beatrix
Honorine
The firm of Nucingen
</pre>

<h2>Redirection</h2>

<p>
File objects can be redirected. In the following example, we redirect the 
standard output to a regular file.
</p>

<pre class="code">
#!/usr/bin/python

# redirect.py

import sys


f = open('output', 'w')
sys.stdout = f

print 'Lucien'
sys.stdout.write('Rastignac\n')
sys.stdout.writelines(['Camusot\n', 'Collin\n'])

sys.stdout = sys.__stdout__

print 'Bianchon'
sys.stdout.write('Lambert\n')
</pre>

<p>
In the redirect.py script, we redirect a standard output to a regular file 
called output. Then we restore the original standard output back. The original 
value of the std.output is kept in a special <code>sys.__stdout__</code>
variable. 
</p>

<pre>
$ ./redirect.py 
Bianchon
Lambert
$ cat output 
Lucien
Rastignac
Camusot
Collin
</pre>


<h2>The open function</h2>

<p>
The <code>open()</code> function is used to open files in our system. 
</p>

<pre>
open(filename, [mode='r'], [bufsize])
</pre>

<p>
The filename is the name of the file to be opened. The mode indicates, how the 
file is going to be opened. For reading, writing, appending etc. The bufsize is 
an optional buffer. It specifies the file's desired buffer size: 0 means unbuffered, 
1 means line buffered, any other positive value means use a buffer of that size. 
A negative bufsize means to use the system default. If omitted, the system default is used.
</p>


<p>
The file modes:
</p>

<table width="250">
<tbody>
<tr>
<th>Mode</th>
<th>Meaning</th>
</tr>

<tr>
<td>r</td><td>Reading</td>
</tr>

<tr class="gray">
<td>w</td><td>Writing</td>
</tr>

<tr>
<td>a</td><td>Appending</td>
</tr>

<tr class="gray">
<td>b</td><td>Binary data</td>
</tr>

<tr>
<td>+</td><td>Updating</td>
</tr>

</tbody>
</table>

<p>
The following little script prints the contents of a file. 
</p>

<pre class="code">
#!/usr/bin/python

# wantme.py

f = open('ifyouwantme', 'r')

for line in f:
   print line,

f.close()
</pre>

<p>
We open a file in read mode. We traverse the contents of the file with the for loop. 
In the end, we close the file object. 
</p>

<pre>
$ ./wantme.py 
Are you really here or am I dreaming
I can't tell dreams from truth 
for it's been so long since I have seen you
I can hardly remember your face anymore 

When I get really lonely
and the distance causes our silence
I think of you smiling 
with pride in your eyes a lover that sighs 

...
</pre>

<p>
In the next example, we do the same. Now we use the <code>readline()</code> method.
</p>

<pre class="code">
#!/usr/bin/python

# wantme2.py

f = open('ifyouwantme', 'r')

while True:
   line = f.readline()
   if not line: break
   else: print line,

f.close()
</pre>

<p>
There is yet another simple way, how we can print the contents of a file. 
Using the <code>readlines()</code>
method. The readlines() method reads all the contents of a file into the 
memory. This is not applicable for very large files, though.
</p>

<pre class="code">
#!/usr/bin/python

# wantme3.py

f = open('ifyouwantme', 'r')

contents = f.readlines()

for i in contents:
   print i,

f.close()
</pre>

<p>
In the next example, we will demonstrate writing to a file. We will 
write a simple strophe into a regular file.
</p>

<pre class="code">
#!/usr/bin/python

# strophe.py

text = """Incompatible, it don't matter though
'cos someone's bound to hear my cry
Speak out if you do
You're not easy to find\n"""


f = open('strophe', 'w')
f.write(text)

f.close()
</pre>

<p>
This time we open the file in a w mode, so that we can write into it. 
If the file does not exist, it is created. 
If it exists, it is overwritten.
</p>

<pre>
$ cat strophe
Incompatible, it don't matter though
'cos someone's bound to hear my cry
Speak out if you do
You're not easy to find
</pre>


<h2>The pickle module</h2>

<p>
So far, we have been working with simple textual data. What if we are 
working with objects rather than simple text? 
For such situations, we can use the <code>pickle</code> module. 
This module serializes Python objects. The Python
objects are converted into byte streams and written to text files. 
This process is called pickling. The inverse operation, reading from a 
file and reconstructing objects is called deserializing or unpickling.  
</p>

<pre class="code">
#!/usr/bin/python

# pickle.py

import pickle

class Person:
   def __init__(self, name, age):
      self.name = name
      self.age = age

   def getName(self):
      return self.name

   def getAge(self):
      return self.age


person = Person('Monica', 15)
print person.getName()
print person.getAge()

f = open('monica', 'w')
pickle.dump(person, f)
f.close()

f = open('monica', 'r')
monica = pickle.load(f)
f.close()

print monica.getName()
print monica.getAge()
</pre>


<p>
In our script, we define a Person class. We create one person. We pickle 
the object using the <code>dump()</code>
method. We close the file, open it again for reading. Unpickle the 
object using the <code>load()</code> method. 
</p>

<pre>
$ ./monica.py 
Monica
15
Monica
15
</pre>

<pre>
$ file monica
monica: ASCII text
</pre>

<p>
The file to which we write is a simple text file. 
</p>


<p>
In this part of the Python tutorial, we covered files. 
</p>


<div class="botNav, center">
<span class="botNavItem"><a href="/">Home</a></span> ‡ <span class="botNavItem"><a href="..">Contents</a></span> ‡ 
<span class="botNavItem"><a href="#">Top of Page</a></span>
</div>


<div class="footer">
<div class="signature">
<a href="/">ZetCode</a> last modified June 15, 2008  <span class="copyright">&copy; 2007 - 2013 Jan Bodnar</span>
</div>
</div>

</div> <!-- content -->

</div> <!-- container -->

</body>
</html>
